from hashlib import md5

from flask import Blueprint,render_template,request,session,jsonify,make_response
from exts import db, mail, cache
from models import UserModel,DistrictModel,AddressModel,EmailCaptchaModel
from flask_mail import Message
import string
import random
from io import BytesIO
from PIL import Image,ImageDraw,ImageFont
import os.path

bp = Blueprint("person", __name__, url_prefix="/person")

# 修改页面
@bp.route("/changePass")
def changePass():
    return render_template("PersonCenter/password.html")

# 用户信息页面
@bp.route("/userInfo")
def userInfo():
    return render_template("PersonCenter/userdata.html")

# 显示地址页面
@bp.route("/showAdd")
def showAdd():
    return render_template("PersonCenter/address.html")

# 添加地址页面
@bp.route("/addAddress")
def addAddress():
    return render_template("PersonCenter/addAddress.html")

# 修改地址页面
@bp.route("/changeAdd")
def changeAdd():
    return render_template("PersonCenter/changeAddress.html")

# 跳转到忘记密码页面
@bp.route("/forgetPass")
def forgetPass1():
    return render_template("Login/password.html")

@bp.route("/forgetPass1")
def forgetPass2():
    return render_template("Login/password_2.html")

@bp.route("/forgetPass2")
def forgetPass3():
    return render_template("Login/password_3.html")

# 发送邮箱验证码
@bp.route("/captcha/email")
def get_email_captcha():
    email=request.args.get("email") # 前端传递邮箱参数
    # 生成4位验证码
    source=string.digits*4
    captcha=random.sample(source,4)
    captcha="".join(captcha)
    message = Message(subject="网上书店重置密码验证码", recipients=[email], body=f"您的验证码是：{captcha}")
    mail.send(message) # 邮箱发送
    # 将验证码存储在cache中时间60秒
    data={'captcha':captcha}
    cache.set('cache_data',data)
    return jsonify({"code":200,"message":"","data":None})

# 重置密码确认
@bp.route("/password/confirm",methods=['POST'])
def passconfirm():
    data=request.get_json() # 获取参数
    email=data['email']
    captcha=data['captcha']
    password1=data['password1']
    password2=data['password2']
    yanzhenma=data['yanzhenma']
    cache_data=cache.get('cache_data')
    # 验证
    if cache_data is None:
        return jsonify({'state':'400','msg':'验证码已过期!'})
    else:
        cache_captcha = cache_data['captcha']
        if captcha==cache_captcha:
            if password1==password2:
                if yanzhenma.lower()==session.get('captcha_text').lower():
                    # 修改密码
                    user=UserModel.query.filter_by(useremail=email).first()
                    print(user.userpassword)
                    user.userpassword=password1
                    db.session.commit()
                    return jsonify({'state': '200', 'msg': '重置成功!'})
                else:
                    return jsonify({'state': '400', 'msg': '验证码错误!'})
            else:
                return jsonify({'state': '400', 'msg': '密码不一致!'})
        else:
            return jsonify({'state': '400', 'msg': '验证码输入错误!'})

# 邮箱测试
@bp.route("/mail/test")
def mail_test():
    message=Message(subject="邮箱测试",recipients=["2518492930@qq.com"],body="这是一条测试邮件")
    mail.send(message)
    return "邮件发送成功"

# 生成验证码
@bp.route('/generate_captcha')
def generate_captcha():
    # 生成验证码图像
    width, height = 120, 40
    im = Image.new('RGB', (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(im)
    font_size = int(height * 0.6)
    font = ImageFont.truetype('arial.ttf', font_size)
    captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))  # 生成6位随机验证码
    text_width, text_height = draw.textsize(captcha_text, font)
    x, y = (width - text_width) // 2, (height - text_height) // 2
    draw.text((x, y), captcha_text, font=font, fill='black')
    # 将图像数据写入内存缓冲区中
    buf = BytesIO()
    im.save(buf, 'jpeg')
    # 生成响应对象
    response = make_response(buf.getvalue())
    response.headers['Content-Type'] = 'image/jpeg'
    # 将验证码文本保存于 session 中用于校验
    session['captcha_text'] = captcha_text
    return response

# 修改密码
@bp.route("/change_Pass",methods=['POST'])
def change_pass():
    data = request.get_json()
    oldpass=data['oldpass']
    newpass=data['newpass']
    renewpass=data['renewpass']
    userid=session.get('user_id')
    user=UserModel.query.filter_by(userid=userid).first()
    print(userid)
    print(data)
    if user.userpassword==oldpass:
        print("正确")
        if newpass==renewpass:
            print("两次密码一致")
            user.userpassword=newpass
            db.session.commit()
            return jsonify({'state':'200','msg':'密码修改成功！'})
        else:
            print("两次密码不一致")
            return jsonify({'state':'200','msg':'两次密码不一致！'})
    else:
        print("原始密码错误")
        return jsonify({'state':'200','msg':'原始密码错误！'})

# 查找用户信息显示在页面中
@bp.route("/get_by_id",methods=['GET'])
def get_by_id():
    userid = session.get('user_id')
    user = UserModel.query.filter_by(userid=userid).first()
    content={'username':user.username,'useremail':user.useremail,'userphone':user.userphone}
    info={'state':200,'data':content}
    print(info)
    return jsonify(info)

# 修改用户信息
@bp.route("/change_info",methods=['POST'])
def change_info():
    name=request.form.get('userName')
    phone=request.form.get('userPhone')
    email=request.form.get('userEmail')
    print(name+" "+phone+" "+email)
    userid = session.get('user_id')
    user = UserModel.query.filter_by(userid=userid).first()
    user.username=name
    user.userphone=phone
    user.useremail=email
    db.session.commit()
    return jsonify({'state':'200','msg':'修改成功！'})

# 根据上一级查询本级列表
@bp.route("/districts",methods=['POST','GET'])
def districts():
    data = request.get_json()
    parent=data['parent']
    print("parent:"+parent)
    districts=DistrictModel.query.filter_by(parent=parent).all()
    print("查询")
    print(districts)
    content={}
    list=[]
    districtlist={}
    for result in districts:
        content={'id':result.id,'parent':result.parent,'code':result.code,'name':result.name}
        list.append(content)
        content={}
    districtlist={'state':200,'data':list}
    print(districtlist)
    return jsonify(districtlist)

# 新增收获地址
@bp.route("/add_new_address",methods=['POST'])
def add_new_address():
    userid = session.get('user_id')
    # 获取添加地址信息
    name=request.form.get('name')
    provinceCode = request.form.get('provinceCode')
    cityCode = request.form.get('cityCode')
    areaCode = request.form.get('areaCode')
    zip = request.form.get('zip')
    address=request.form.get('address')
    phone=request.form.get('phone')
    tel=request.form.get('tel')
    tag=request.form.get('tag')
    print(name+"-"+provinceCode+"-"+cityCode+"-"+areaCode+"-"+zip+"-"+address+"-"+phone+"-"+tel+"-"+tag)
    # 最多只能添加5个地址
    count = db.session.query(AddressModel).filter_by(uid=userid).count()
    print(count)
    if count<5:
        province=findNameByCode(provinceCode)
        city=findNameByCode(cityCode)
        area=findNameByCode(areaCode)
        isDefault=(1 if count==0 else 0)
        insertAdd=AddressModel(uid=userid,name=name,province_name=province,province_code=provinceCode,city_name=city,city_code=cityCode,
                               area_name=area,area_code=areaCode,zip=zip,address=address,phone=phone,tel=tel,tag=tag,is_default=isDefault)
        db.session.add(insertAdd)
        db.session.commit()
        return jsonify({'state':'200','message':"添加收获地址成功！"})
    else:
        return jsonify({'state':'400','message':"最多只能添加5条地址！"})

# 根据code查找名字
def findNameByCode(code):
    district=DistrictModel.query.filter_by(code=code).first()
    return district.name

# 显示用户收货地址
@bp.route("/address",methods=['GET'])
def address():
    userid = session.get('user_id')
    addresses=AddressModel.query.filter_by(uid=userid).order_by(AddressModel.is_default.desc()).all()
    content = {}
    list=[]
    for address in addresses:
        content={'aid':address.aid,'uid':address.uid,'provinceName':address.province_name,'cityName':address.city_name,
                 'areaName':address.area_name,'address':address.address,'phone':address.phone,'tag':address.tag,'name':address.name}
        list.append(content)
        content={}
    addressList={'state':200,'data':list}
    print(addressList)
    return jsonify(addressList)

# 显示地址详细信息
@bp.route("/change_address",methods=['POST'])
def change_address():
    data=request.get_json()
    aid=data['aid']
    print(aid)
    userid = session.get('user_id')
    address=AddressModel.query.filter_by(aid=aid,uid=userid).first()
    content = {'aid': address.aid, 'uid': address.uid, 'provinceName': address.province_name,'provinceCode':address.province_code,
               'cityName': address.city_name,'cityCode':address.city_code,'areaName': address.area_name,'areaCode':address.area_code,
               'address': address.address, 'phone': address.phone, 'tag': address.tag,'name': address.name,'tel':address.tel,'zip':address.zip}
    print(content)
    return jsonify({'data':content})

# 修改地址
@bp.route("/change/<aid>",methods=['POST'])
def change(aid):
    print("传递参数："+aid)
    userid = session.get('user_id')
    # 获取添加地址信息
    name = request.form.get('name')
    print("姓名："+name)
    provinceCode = request.form.get('provinceCode')
    print("provinceCode:"+provinceCode)
    cityCode = request.form.get('cityCode')
    areaCode = request.form.get('areaCode')
    zip = request.form.get('zip')
    address = request.form.get('address')
    phone = request.form.get('phone')
    tel = request.form.get('tel')
    tag = request.form.get('tag')
    province = findNameByCode(provinceCode)
    print("province:"+province)
    city = findNameByCode(cityCode)
    area = findNameByCode(areaCode)
    address1 = AddressModel.query.filter_by(aid=aid, uid=userid).first()
    if address:
        address1.name=name
        address1.province_name=province
        address1.province_code=provinceCode
        address1.city_name=city
        address1.city_code=cityCode
        address1.area_name=area
        address1.area_code=areaCode
        address1.zip=zip
        address1.address=address
        address1.phone=phone
        address1.tel=tel
        address1.tag=tag
        db.session.commit()
        return jsonify({'state':'200','msg':'修改地址成功！'})
    return jsonify({'state':'300','msg':'修改地址失败！'})

# 设置默认地址(默认地址is_default=1)
@bp.route("/address/set_default/<aid>",methods=['POST'])
def set_default(aid):
    print(aid)
    userid = session.get('user_id')
    # 设置uid的所有地址的is_default=0
    address = AddressModel.query.filter_by(uid=userid).all()
    for a in address:
        a.is_default=0
    db.session.commit()
    # 设置aid的is_default=1
    address1 = AddressModel.query.filter_by(aid=aid, uid=userid).first()
    address1.is_default=1
    db.session.commit()
    return jsonify({'state':"200"})

# 删除地址
@bp.route("/address/deleteAddress/<aid>",methods=['POST'])
def deleteAddress(aid):
    print(aid)
    userid = session.get('user_id')
    address=AddressModel.query.filter_by(aid=aid).first()
    isDefault=address.is_default
    print("isDefault:"+str(isDefault))
    if address:
        db.session.delete(address)
        db.session.commit()
    count=AddressModel.query.filter_by(uid=userid).count()
    if count==0:
        print("删除一条数据成功")
        return jsonify({'state':'200','msg':"删除一条地址成功!"})
    else:
        if isDefault == 0:
            print("删除的不是默认地址")
            return jsonify({'state':'200','msg':"删除非默认地址成功！"})
        else:
           address1=AddressModel.query.filter_by(uid=userid).first()
           address1.is_default=1
           db.session.commit()
           return jsonify({'state': '200', 'msg': "删除默认地址成功,自动设置第一条为默认地址！"})

# 退出登录
@bp.route("/logout")
def logout():
    session.pop("user_id",None)
    return render_template("Login/login.html")

# 头像上传
# 图片上传
@bp.route("/uploadImg",methods=['POST'])
def uploadImg():
    global filename
    file=request.files['file']
    if file:
        filename=file.filename
        print(filename)
        file.save(os.path.join('static/image/头像','头像.png'))
    return jsonify({'code':'0','filename':filename})